#pragma once

#include <iostream>
#include <cstdlib>
#include <string>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/sem.h>
#include <fcntl.h>

const std::string pathname = "/home/liuty/src/remote-gitcode/_proc_IPC/shm";

const int proj_id = 0x1122ff44;

const int size = 4096; // OS以4096为单位分配实际内存，size建议设置为4096的倍数

const std::string filename = "fifo";

key_t getKey()
{
    key_t key = ftok(pathname.c_str(), proj_id);
    if (key < 0)
    {
        std::cerr << "errno: " << errno << ", errstring: " << strerror(errno) << std::endl;
        exit(1);
    }
    return key;
}

std::string toHex(int num)
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "0x%x", num);
    return buffer;
}

int shmHelper(int key, int flag)
{
    int shmid = shmget(key, size, flag); // 设置权限
    if (shmid < 0)
    {
        std::cerr << "errno: " << errno << ", errstring: " << strerror(errno) << std::endl;
        return 1;
    }
    return shmid;
}

int createShm(int key)
{
    return shmHelper(key, IPC_CREAT | IPC_EXCL | 0644);
}

int getShm(int key)
{
    return shmHelper(key, IPC_CREAT);
}

bool makeFifo()
{
    int n = mkfifo(filename.c_str(), 0666);
    if (n < 0)
    {
        std::cerr << "errno: " << errno << ", errstring: " << strerror(errno) << std::endl;
        return false;
    }
    return true;
}